package com.example.demo;

import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureOkHttpExample {

    private final OkHttpClient client = new OkHttpClient();

    public CompletableFuture<String> asyncHttpRequest(String url) {
        // https://jsonplaceholder.typicode.com/posts/2
//        return CompletableFuture.supplyAsync(() -> {
//            Request request = new Request.Builder()
//                    .url(url)
//                    .build();
//
//            try (Response response = client.newCall(request).execute()) {
//                if (response.isSuccessful() && response.body() != null) {
//                    return response.body().string();
//                } else {
//                    throw new IOException("Unexpected code " + response);
//                }
//            } catch (IOException e) {
//                throw new RuntimeException("Request failed: " + e.getMessage(), e);
//            }
//        });
        //
        CompletableFuture<String> future = new CompletableFuture<>();

        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                future.completeExceptionally(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful() && response.body() != null) {
                    future.complete(response.body().string());
                } else {
                    future.completeExceptionally(new IOException("Unexpected code " + response));
                }
            }
        });

        return future;
    }

    public static void main(String[] args) throws Exception{
        new CompletableFutureOkHttpExample().start();
    }

    public void start() throws InterruptedException, ExecutionException {
        CompletableFuture<String> future1 = asyncHttpRequest(url("1", ""));

        CompletableFuture<String> future2 = future1.thenCompose(result1 -> {
            return asyncHttpRequest(url("2", result1));
        });

        CompletableFuture<String> future3 = future2.thenCompose(result2 -> {
            return asyncHttpRequest(url("3", result2));

        });

        future3.thenAccept(result3 -> {
            System.out.println("Task 3 Result: " + result3);
            System.out.println("All tasks completed.");
            client.dispatcher().executorService().shutdown();
        }).join();
    }


    private String url(String s, String s2) {
        int len = s2.length() >= 30 ? 30 : s2.length();
        return "http://httpbin.org/get?param1=" + s + "&param2=" + s2.substring(0, len);
    }
}
